<!-- 问诊队列 -->
<template>
	<el-container>
		<el-header>
			<NavMenu activeIndex="1" />
		</el-header>
		<el-container>
			<el-main>
				<el-affix target=".el-main" :offset="60">
					<el-button text :icon="Microphone" @click="onCall" :disabled="isOperationsDisabled">叫号</el-button>
					<el-popconfirm title="确认完成问诊？" :icon="DocumentChecked" @confirm="onComplete">
						<template #reference>
							<el-button text :icon="DocumentChecked" :disabled="isOperationsDisabled">完成问诊</el-button>
						</template>
					</el-popconfirm>
					<el-popconfirm title="确认挂起病人？" :icon="Timer" @confirm="onHang">
						<template #reference>
							<el-button text :icon="Timer" :disabled="isOperationsDisabled">挂起</el-button>
						</template>
					</el-popconfirm>
				</el-affix>
				<div class="paper">
					<div style="padding: 2%;">
						<el-table ref="tableRef" :data="tableData" row-key="regID" :max-height="1600"
							highlight-current-row @current-change="onTableCurrentChange">
							<el-table-column prop="regID" label="预约号" />
							<el-table-column prop="period" label="预约时段" />
							<el-table-column label="预约状态" :filter-multiple="false"
								:filters="[{ text: '排队中', value: 'Paid' },{ text: '未缴费', value: 'NotPaid' },{ text: '已就诊', value: 'Completed' },{ text: '已挂起', value: 'Canceled' }]"
								:filter-method="onTableFilterStatus">
								<template #default="scope">
									<el-tag disable-transitions
										:type="{'Paid':'primary', 'NotPaid':'info', 'Completed':'success', 'Canceled':'warning'}[scope.row.status]">
										{{{'Paid':'排队中', 'NotPaid':'未缴费', 'Completed':'已就诊', 'Canceled':'已挂起'}[scope.row.status]}}
									</el-tag>
								</template>
							</el-table-column>
							<el-table-column prop="name" label="姓名" />
							<el-table-column prop="sex" label="性别" />
							<el-table-column prop="age" label="年龄" />
							<el-table-column prop="tel" label="电话" />
						</el-table>
					</div>
				</div>
			</el-main>
			<el-aside style="border-left: var(--el-border);">
				<Card title="今日数据">
					<el-row>
						<el-col :span="12" class="square-box">
							<el-statistic title="已预约" :value="statistics.numRegistered" />
						</el-col>
						<el-col :span="12" class="square-box">
							<el-statistic title="排队中" :value="statistics.numQueuing" />
						</el-col>
						<el-col :span="12" class="square-box">
							<el-statistic title="已就诊" :value="statistics.numCompleted" />
						</el-col>
						<el-col :span="12" class="square-box">
							<el-statistic title="已挂起" :value="statistics.numCanceled" />
						</el-col>
					</el-row>
				</Card>
			</el-aside>
		</el-container>
	</el-container>
</template>

<script lang="ts" setup>
	import { onShow, onHide } from '@dcloudio/uni-app';
	import { ref, onMounted, onUnmounted, computed } from 'vue';
	import axiosInstance from '@/Config/axiosConfig';
	import globalStore from '@/store/GlobalStore';
	import Emessage from '@/Utils/Message';
	import { Microphone, DocumentChecked, Timer } from '@element-plus/icons-vue';
	import { ElNotification, type TableInstance } from 'element-plus';
	import '@/pages/doctor/styles/common.scss';
	import { birthday2age, integer2sex, encodeDate } from '@/pages/doctor/scripts/common.ts';
	import NavMenu from '@/pages/doctor/components/NavMenu';
	import Card from '@/pages/doctor/components/Card';

	const docID = uni.getStorageSync('id');
	if (!docID) {
		uni.redirectTo({url:'/'});
	}
	
	// 问诊队列
	const tableRef = ref<TableInstance>();
	const tableData = ref([]);
	const chosenRegID = ref(null);
	const chosenRow = computed(() => {
		const index = tableData.value.findIndex(row => row.regID === chosenRegID.value);
		return index == -1 ? null : tableData.value[index];
	});
	const isOperationsDisabled = computed(() => !(chosenRow.value && chosenRow.value.status == 'Paid'));
	const allPossiblePeriods = ['08:00:00~08:30:00', '08:30:00~09:00:00', '09:00:00~09:30:00', '09:30:00~10:00:00', '10:00:00~10:30:00', '10:30:00~11:00:00', '11:00:00~11:30:00', '11:30:00~12:00:00', '14:00:00~14:30:00', '14:30:00~15:00:00', '15:00:00~15:30:00', '15:30:00~16:00:00', '16:00:00~16:30:00', '16:30:00~17:00:00'];
	let getTableDataInterval = null;

	const getTableData = async () => {
		// 更新队列数据
		try {
			const today = encodeDate(new Date());
			const response = await axiosInstance.get('/doc/getQueueListByDocId?docId=' + docID);
			if (response.status == 200) {
				const dict = {}; // dict[时段][病人ID] -> 病人次序
				const queues = response.data;
				console.log(queues)
				queues.forEach(queue => {
					if (!(queue.period in dict))
						dict[queue.period] = {};
					for (var i = 0; i < queue.patients.length; i++) {
						var patient = queue.patients[i];
						dict[queue.period][patient.id] = i;
					}
				});
				const response2 = await axiosInstance.get('/doc/getAllPatientsByIdAndDate?docId=' + docID + "&date=" + today);
				if (response2.status == 200) {
					const rows = response2.data.map(x => {
						const r = x.reg_info;
						const p = x.patient_info;
						return {
							regID: r.id,
							status: r.status,
							period: r.appointment_period,
							patientID: p.id,
							name: p.name,
							age: birthday2age(new Date(p.birthday)),
							sex: integer2sex(p.sex),
							tel: p.tel,
						};
					});
					rows.sort((a, b) => {
						if (a.status != b.status) {
							const m = { 'Paid': 0, 'NotPaid': 1, 'Completed': 2, 'Canceled': 3 };
							return m[a.status] - m[b.status];
						} else {
							if (a.period != b.period) {
								return a.period < b.period ? -1 : 1;
							} else {
								const m = dict[a.period];
								return m ? m[a.patientID] - m[b.patientID] : 0;
							}
						}
					});
					tableData.value = rows;
				} else {
					ElNotification({ title: response2.status, message: response2.statusText, type: 'error', duration: 3000 });
				}
			} else {
				ElNotification({ title: response.status, message: response.statusText, type: 'error', duration: 3000 });
			}
		} catch (e) {
			ElNotification({ title: '错误', message: '无法连接服务器！', type: 'error', duration: 3000 });
		}
	};

	const onTableCurrentChange = (currentRow, oldCurrentRow) => {
		if (currentRow) {
			if (chosenRegID.value != currentRow.regID) {
				const doctorCurrentPatient = {
					regID: currentRow.regID,
					patientID: currentRow.patientID,
				};
				uni.setStorageSync('doctorCurrentPatient', doctorCurrentPatient);
				chosenRegID.value = currentRow.regID;
			}
		} else {
			tableRef.value.setCurrentRow(chosenRow.value);
		}
	}

	const onTableFilterStatus = (value : string, row : any) => {
		return row.status === value;
	}

	const onCall = () => {
		// 叫号
		if (chosenRow.value) {
			ElNotification({ title: '叫号', message: '请' + chosenRow.value.regID + '号病人就诊。', type: 'info', duration: 3000 });
		}
	}

	const onComplete = async () => {
		// 完成问诊
		try {
			const response = await axiosInstance.post('/doc/updateRegStatusByRegId?regId=' + chosenRegID.value + "&status=Completed");
			if (response.status == 200) {
				const data = response.data;
				ElNotification({ title: '完成', message: '结束' + chosenRegID.value + '号病人的接诊。', type: 'success', duration: 3000 });
			} else {
				ElNotification({ title: response.status, message: response.statusText, type: 'error', duration: 3000 });
			}
		} catch (e) {
			ElNotification({ title: '错误', message: '无法连接服务器！', type: 'error', duration: 3000 });
		}
		getTableData();
	}

	const onHang = async () => {
		// 挂起
		try {
			const response = await axiosInstance.post('/doc/updateRegStatusByRegId?regId=' + chosenRegID.value + "&status=Canceled");
			if (response.status == 200) {
				const data = response.data;
				ElNotification({ title: '挂起', message: '已挂起' + chosenRegID.value + '号病人。', type: 'info', duration: 3000 });
			} else {
				ElNotification({ title: response.status, message: response.statusText, type: 'error', duration: 3000 });
			}
		} catch (e) {
			ElNotification({ title: '错误', message: '无法连接服务器！', type: 'error', duration: 3000 });
		}
		getTableData();
	}

	getTableData();

	onShow(() => {
		// 定时更新队列数据
		getTableDataInterval = setInterval(getTableData, 10000);
	});

	onHide(() => {
		if (getTableDataInterval !== null) {
			clearInterval(getTableDataInterval);
			getTableDataInterval = null;
		}
	});
	onUnmounted(()=>{
		if (getTableDataInterval !== null) {
			clearInterval(getTableDataInterval);
			getTableDataInterval = null;
		}
	})

	// 今日数据
	const statistics = computed(() => {
		const counts = {};
		tableData.value.forEach(row => {
			counts[row.status] = (counts[row.status] || 0) + 1;
		});
		return { numRegistered: tableData.value.length, numQueuing: counts['Paid'], numCompleted: counts['Completed'], numCanceled: counts['Canceled'] };
	});
</script>

<style lang="scss" scoped>
	@import 'styles/common.scss';

	.square-box {
		@extend .flex-center;
		aspect-ratio: 1 / 1;
	}
</style>